﻿using Azure;
using Microsoft.EntityFrameworkCore;
using QModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace QServices.Services
{
	public partial class PigeonCageService : QMainService
	{

		public List<PigeonCage> GetPigeonCageList()
		{
			var db = CreateDbContext();
			var res = db.Set<PigeonCage>().ToList();
			return res;
		}

		public PigeCageDto GetPigeCageDtoProce(string areaName)
		{
			using var db = CreateDbContext();
			var sql = $" GetPigeCageDto '{areaName}',{AppRuntime.MinTemperature},{AppRuntime.MaxTemperature}";
			var res = db.Database.SqlQueryRaw<PigeCageDto>(sql).ToList().FirstOrDefault() ?? new PigeCageDto();
			return res;
		}

		public List<PigeonCage> GetPigeonCageListByArea(string areaName)
		{
			var db = CreateDbContext();
			var query = db.Set<PigeonCage>().AsQueryable();
			if (!string.IsNullOrWhiteSpace(areaName)) query = query.Where(x => x.Building == areaName);
			var res = query.ToList();
			return res;
		}
		public int GetPigeonCageCount()
		{
			var db = CreateDbContext();
			var res = db.Set<PigeonCage>().Count();
			return res;
		}

		public (List<PigeonCageQuery> lst, int total) GetPigeonCageQueryList(PigeonCondition condition, int Page = 1, int PageSize = 20)
		{
			using var db = CreateDbContext();
			var sb_count = new StringBuilder();
			var sb = new StringBuilder();
			var temp_sql = $@"WITH TemperatureData AS (
    SELECT 
        pc.ID,
        MAX(TRY_CAST(temperatures.value AS float)) AS MaxTemperature,
        MIN(TRY_CAST(temperatures.value AS float)) AS MinTemperature
    FROM 
        [dbo].[PigeonCage] pc
    CROSS APPLY 
        OPENJSON(pc.temperature) WITH (value nvarchar(50) '$') AS temperatures
    GROUP BY 
        pc.ID
)";



			var tt_count = $@"
								SELECT  count(1) as total
from PigeonCage cage  
left JOIN  PigeonChild as child ON  cage.ID = child.PigeonHouseID
left JOIN  PigeonEgg as egg ON cage.ID=egg.PigeonHouseID     
";

			var tt = $@"
				SELECT  cage.ID,cage.Building,cage.Arrange,cage.[Group],cage.Number, cage.BreedingPigeonCount as PigeonCount,cage.BreedingPigeonCreateDate  as PigeonDate, 0.00 as DailyGrams, 
					0 as F1,0 as F2, 0 as F3 ,0 as FT1, 0 as FT2, 0 as FT3,
					cage.temperature  as Temperature,
				child.ChildNumber as RuGeCount,child.CreateDate as ChildDate,1 as RuGeDay,
				egg.EggNumber as EggCount ,egg.CreateDate as EggDate,egg.IsFertilization as IsFertilization,1 as EggDay
from PigeonCage cage  
left JOIN  PigeonChild as child ON  cage.ID = child.PigeonHouseID
left JOIN  PigeonEgg as egg ON cage.ID=egg.PigeonHouseID  
			";
			sb.AppendLine(tt);
			sb_count.AppendLine(tt_count);
			var Index = 0;

			if (condition != null && condition.TempStatus > 0)
			{
				var ct_0 = $"  left join  TemperatureData tt ON cage.ID = tt.ID  ";
				var ct_1 = ""; var ct_2 = "";

				ct_1 += $"where ( tt.MaxTemperature>{AppRuntime.MaxTemperature} or tt.MinTemperature<{AppRuntime.MinTemperature}) ";
				ct_2 += $" where ( tt.MaxTemperature<={AppRuntime.MaxTemperature} and tt.MinTemperature>={AppRuntime.MinTemperature}) ";
				sb.AppendLine(ct_0);
				sb_count.AppendLine(ct_0);
				if (condition.TempStatus == 1)
				{
					sb.AppendLine(ct_2);
					sb_count.AppendLine(ct_2);
				}
				else
				{
					sb.AppendLine(ct_1);
					sb_count.AppendLine(ct_1);
				}
				sb.Insert(0, temp_sql);
				sb_count.Insert(0, temp_sql);
				Index++;

			}

			if (condition != null && !string.IsNullOrWhiteSpace(condition.Region))
			{
				var ct_0 = "";
				if (Index == 0)
				{
					ct_0 += " where ";
				}
				ct_0 += $"  cage.Building='{condition.Region}'";
				sb.AppendLine(ct_0);
				sb_count.AppendLine(ct_0);
				Index++;
			}

			if (condition != null && !string.IsNullOrWhiteSpace(condition.CageNumber))
			{
				condition.CageNumber = condition.CageNumber.Replace("-", "").Replace("_", "");
				var ct_0 = "";
				if (Index == 0) ct_0 += " where ";
				else ct_0 += " and ";
				ct_0 += $"   cage.ID  like '%{condition.CageNumber}%'";
				Index++;
				sb.AppendLine(ct_0);
				sb_count.AppendLine(ct_0);
			}
			if (condition != null && condition.HasRuGe > 0)
			{
				var ct_1 = " ";
				if (Index == 0) ct_1 = " where ";
				else ct_1 = "  and ";

				if (condition.HasRuGe == 1) ct_1 += " (child.ChildNumber=0 or child.ChildNumber is NULL)";
				else ct_1 += " child.ChildNumber>0 ";

				Index++;
				sb.AppendLine(ct_1);
				sb_count.AppendLine(ct_1);

			}
			if (condition != null && condition.HasEgg > 0)
			{
				var ct_1 = " ";
				if (Index == 0) ct_1 = "  where ";
				else ct_1 = "   and ";

				if (condition.HasEgg == 1) ct_1 += " (egg.EggNumber=0 or egg.EggNumber is NULL)";
				else ct_1 += " egg.EggNumber>0 ";
				Index++;
				sb.AppendLine(ct_1);
				sb_count.AppendLine(ct_1);
			}

			if (condition != null && condition.CageStatus > 0)
			{
				/**
				 new UseModel{Name="所有",Value=0},
			new UseModel{Name="空置鸽笼",Value=1 },
			new UseModel{Name="查蛋",Value=2},
			new UseModel{Name="照蛋",Value=3},
			new UseModel{Name="查雏",Value=4},
			new UseModel{Name="出栏",Value=5},
			new UseModel{Name="淘汰",Value=6},
			new UseModel{Name="补栏",Value=7},
			new UseModel{Name="调并",Value=8}
				 
				 */

				var ct_0 = "";
				if (Index == 0) ct_0 = "  where ";
				else ct_0 = "  and ";
				if (condition.CageStatus == 1)
				{
					ct_0 += " (cage.NeedMatter like '%8%' or cage.BreedingPigeonCount=0 or cage.BreedingPigeonCount is null)";
				}
				else if (condition.CageStatus == 2)
				{
					ct_0 += " (cage.NeedMatter like '%1%')";
				}
				else if (condition.CageStatus == 3)
				{
					ct_0 += " (cage.NeedMatter like '%2%')";
				}
				else if (condition.CageStatus == 4)
				{
					ct_0 += " (cage.NeedMatter like '%3%')";
				}
				else if (condition.CageStatus == 5)
				{
					ct_0 += " (cage.NeedMatter like '%4%')";
				}
				else if (condition.CageStatus == 6)
				{
					ct_0 += " (cage.NeedMatter like '%5%')";
				}
				else if (condition.CageStatus == 7)
				{
					ct_0 += " (cage.NeedMatter like '%7%')";
				}
				else if (condition.CageStatus == 8)
				{
					ct_0 += " (cage.NeedMatter like '%6%')";
				}
				else if (condition.CageStatus == 9)
				{
					ct_0 += " (cage.NeedMatter like '%0%')";
				}

				Index++;
				sb.AppendLine(ct_0);
				sb_count.AppendLine(ct_0);

			}





			sb.AppendLine($"  ORDER BY cage.ID   offset {(Page - 1) * PageSize} rows fetch next {PageSize} rows only");
			var sql = sb.ToString();
			var sql_count = sb_count.ToString();
			var total = db.Database.SqlQueryRaw<PigeonConditionCount>(sql_count).ToList().First();
			var res = db.Database.SqlQueryRaw<PigeonCageQuery>(sql).ToList();
			if (res.Count > 0)
			{
				var feedDatas = GetTodayAgvErrorData();
				res.ForEach(x =>
				{

					if (!x.RuGeDay.HasValue) x.RuGeDay = 0;
					if (!x.EggDay.HasValue) x.EggDay = 0;
					if (!x.RuGeCount.HasValue)
					{
						x.RuGeCount = 0;
						x.RuGeDay = 0;
					}
					if (!x.EggCount.HasValue)
					{
						x.EggCount = 0;
						x.EggDay = 0;
					}
					if (!x.IsFertilization.HasValue) x.IsFertilization = false;
					if (x.ChildDate.HasValue)
					{
						x.RuGeDay = int.Parse(Math.Ceiling((DateTime.Now - x.ChildDate.Value).TotalDays).ToString());
					}
					if (x.EggDate.HasValue)
					{
						x.EggDay = int.Parse(Math.Ceiling((DateTime.Now - x.EggDate.Value).TotalDays).ToString());
					}
					if (x.RuGeCount.HasValue && x.RuGeDay.HasValue)
					{
						var childCount = x.RuGeDay <= AppRuntime.SmallPigeon.Count ? x.RuGeDay : 0;
						var feed = x.RuGeDay <= AppRuntime.SmallPigeon.Count ? AppRuntime.SmallPigeon[x.RuGeDay.Value] : 0;
						x.DailyGrams = AppRuntime.BigPigeon * x.PigeonCount + x.RuGeCount * feed;
						if (x.DailyGrams < 40) x.DailyGrams = 0;
						else if (x.DailyGrams <= 80) x.DailyGrams = 80;
						else if (x.DailyGrams <= 120) x.DailyGrams = 120;
						else if (x.DailyGrams <= 160) x.DailyGrams = 160;
						else if (x.DailyGrams <= 200) x.DailyGrams = 200;
					}

					if (feedDatas.ContainsKey(x.Id))
					{
						var feedData = feedDatas[x.Id];
						x.F1 = feedData.F1;
						x.F2 = feedData.F2;
						x.F3 = feedData.F3;
						x.FT1 = feedData.FT1;
						x.FT2 = feedData.FT2;
						x.FT3 = feedData.FT3;
					}

				});
			}
			return (res, total.total);


		}

		public List<PigeonCageQuery> GetPigeonCageQueriyAll(PigeonCondition condition)
		{
			using var db = CreateDbContext();
			var sb_count = new StringBuilder();
			var sb = new StringBuilder();
			var temp_sql = $@"WITH TemperatureData AS (
    SELECT 
        pc.ID,
        MAX(TRY_CAST(temperatures.value AS float)) AS MaxTemperature,
        MIN(TRY_CAST(temperatures.value AS float)) AS MinTemperature
    FROM 
        [dbo].[PigeonCage] pc
    CROSS APPLY 
        OPENJSON(pc.temperature) WITH (value nvarchar(50) '$') AS temperatures
    GROUP BY 
        pc.ID
)";



			var tt_count = $@"
								SELECT  count(1) as total
from PigeonCage cage  
left JOIN  PigeonChild as child ON  cage.ID = child.PigeonHouseID
left JOIN  PigeonEgg as egg ON cage.ID=egg.PigeonHouseID     
";

			var tt = $@"
				SELECT  cage.ID,cage.Building,cage.Arrange,cage.[Group],cage.Number, cage.BreedingPigeonCount as PigeonCount,cage.BreedingPigeonCreateDate  as PigeonDate, 0.00 as DailyGrams, 
				0 as F1,0 as F2, 0 as F3 ,0 as FT1, 0 as FT2, 0 as FT3,
				cage.temperature  as Temperature,
				child.ChildNumber as RuGeCount,child.CreateDate as ChildDate,1 as RuGeDay,
				egg.EggNumber as EggCount ,egg.CreateDate as EggDate,egg.IsFertilization as IsFertilization,1 as EggDay
from PigeonCage cage  
left JOIN  PigeonChild as child ON  cage.ID = child.PigeonHouseID
left JOIN  PigeonEgg as egg ON cage.ID=egg.PigeonHouseID  
			";
			sb.AppendLine(tt);
			sb_count.AppendLine(tt_count);
			var Index = 0;

			if (condition != null && condition.TempStatus > 0)
			{
				var ct_0 = $"  left join  TemperatureData tt ON cage.ID = tt.ID  ";
				var ct_1 = ""; var ct_2 = "";

				ct_1 += $"where ( tt.MaxTemperature>{AppRuntime.MaxTemperature} or tt.MinTemperature<{AppRuntime.MinTemperature}) ";
				ct_2 += $" where ( tt.MaxTemperature<={AppRuntime.MaxTemperature} and tt.MinTemperature>={AppRuntime.MinTemperature}) ";
				sb.AppendLine(ct_0);
				sb_count.AppendLine(ct_0);
				if (condition.TempStatus == 1)
				{
					sb.AppendLine(ct_2);
					sb_count.AppendLine(ct_2);
				}
				else
				{
					sb.AppendLine(ct_1);
					sb_count.AppendLine(ct_1);
				}
				sb.Insert(0, temp_sql);
				sb_count.Insert(0, temp_sql);
				Index++;

			}

			if (condition != null && !string.IsNullOrWhiteSpace(condition.Region))
			{
				var ct_0 = "";
				if (Index == 0)
				{
					ct_0 += " where ";
				}
				ct_0 += $"  cage.Building='{condition.Region}'";
				sb.AppendLine(ct_0);
				sb_count.AppendLine(ct_0);
				Index++;
			}

			if (condition != null && !string.IsNullOrWhiteSpace(condition.CageNumber))
			{
				condition.CageNumber = condition.CageNumber.Replace("-", "").Replace("_", "");
				var ct_0 = "";
				if (Index == 0) ct_0 += " where ";
				else ct_0 += " and ";
				ct_0 += $"   cage.ID  like '%{condition.CageNumber}%'";
				Index++;
				sb.AppendLine(ct_0);
				sb_count.AppendLine(ct_0);
			}
			if (condition != null && condition.HasRuGe > 0)
			{
				var ct_1 = " ";
				if (Index == 0) ct_1 = " where ";
				else ct_1 = "  and ";

				if (condition.HasRuGe == 1) ct_1 += " (child.ChildNumber=0 or child.ChildNumber is NULL)";
				else ct_1 += " child.ChildNumber>0 ";

				Index++;
				sb.AppendLine(ct_1);
				sb_count.AppendLine(ct_1);

			}
			if (condition != null && condition.HasEgg > 0)
			{
				var ct_1 = " ";
				if (Index == 0) ct_1 = "  where ";
				else ct_1 = "   and ";

				if (condition.HasEgg == 1) ct_1 += " (egg.EggNumber=0 or egg.EggNumber is NULL)";
				else ct_1 += " egg.EggNumber>0 ";
				Index++;
				sb.AppendLine(ct_1);
				sb_count.AppendLine(ct_1);
			}

			if (condition != null && condition.CageStatus > 0)
			{
				/**
				 new UseModel{Name="所有",Value=0},
			new UseModel{Name="空置鸽笼",Value=1 },
			new UseModel{Name="查蛋",Value=2},
			new UseModel{Name="照蛋",Value=3},
			new UseModel{Name="查雏",Value=4},
			new UseModel{Name="出栏",Value=5},
			new UseModel{Name="淘汰",Value=6},
			new UseModel{Name="补栏",Value=7},
			new UseModel{Name="调并",Value=8}
				 
				 */

				var ct_0 = "";
				if (Index == 0) ct_0 = "  where ";
				else ct_0 = "  and ";
				if (condition.CageStatus == 1)
				{
					ct_0 += " (cage.NeedMatter like '%8%' or cage.BreedingPigeonCount=0 or cage.BreedingPigeonCount is null)";
				}
				else if (condition.CageStatus == 2)
				{
					ct_0 += " (cage.NeedMatter like '%1%')";
				}
				else if (condition.CageStatus == 3)
				{
					ct_0 += " (cage.NeedMatter like '%2%')";
				}
				else if (condition.CageStatus == 4)
				{
					ct_0 += " (cage.NeedMatter like '%3%')";
				}
				else if (condition.CageStatus == 5)
				{
					ct_0 += " (cage.NeedMatter like '%4%')";
				}
				else if (condition.CageStatus == 6)
				{
					ct_0 += " (cage.NeedMatter like '%5%')";
				}
				else if (condition.CageStatus == 7)
				{
					ct_0 += " (cage.NeedMatter like '%7%')";
				}
				else if (condition.CageStatus == 8)
				{
					ct_0 += " (cage.NeedMatter like '%6%')";
				}
				else if (condition.CageStatus == 9)
				{
					ct_0 += " (cage.NeedMatter like '%0%')";
				}

				Index++;
				sb.AppendLine(ct_0);
				sb_count.AppendLine(ct_0);

			}






			var sql = sb.ToString();
			var sql_count = sb_count.ToString();
			var total = db.Database.SqlQueryRaw<PigeonConditionCount>(sql_count).ToList().First();
			var res = db.Database.SqlQueryRaw<PigeonCageQuery>(sql).ToList();
			if (res.Count > 0)
			{
				res.ForEach(x =>
				{

					if (!x.RuGeDay.HasValue) x.RuGeDay = 0;
					if (!x.EggDay.HasValue) x.EggDay = 0;
					if (!x.RuGeCount.HasValue)
					{
						x.RuGeCount = 0;
						x.RuGeDay = 0;
					}
					if (!x.EggCount.HasValue)
					{
						x.EggCount = 0;
						x.EggDay = 0;
					}
					if (!x.IsFertilization.HasValue) x.IsFertilization = false;
					if (x.ChildDate.HasValue)
					{
						x.RuGeDay = int.Parse(Math.Ceiling((DateTime.Now - x.ChildDate.Value).TotalDays).ToString());
					}
					if (x.EggDate.HasValue)
					{
						x.EggDay = int.Parse(Math.Ceiling((DateTime.Now - x.EggDate.Value).TotalDays).ToString());
					}
					if (x.RuGeCount.HasValue && x.RuGeDay.HasValue)
					{
						var childCount = x.RuGeDay <= AppRuntime.SmallPigeon.Count ? x.RuGeDay : 0;
						var feed = x.RuGeDay <= AppRuntime.SmallPigeon.Count ? AppRuntime.SmallPigeon[x.RuGeDay.Value] : 0;
						x.DailyGrams = AppRuntime.BigPigeon * x.PigeonCount + x.RuGeCount * feed;
						if (x.DailyGrams < 40) x.DailyGrams = 0;
						else if (x.DailyGrams <= 80) x.DailyGrams = 80;
						else if (x.DailyGrams <= 120) x.DailyGrams = 120;
						else if (x.DailyGrams <= 160) x.DailyGrams = 160;
						else if (x.DailyGrams <= 200) x.DailyGrams = 200;
					}


				});
			}
			return res;
		}

		public (bool IsError, string msg) ImpoertPigeonCageData(List<PigeonCageQuery> lst)
		{
			var IsError = false;
			var msg = "";
			var db = CreateDbContext();
			var dic = new Dictionary<string, (int Index, PigeonCageQuery Info)>();

			for (int i = 0; i < lst.Count; i++)
			{
				var cage = lst[i];
				if (dic.ContainsKey(cage.Id))
				{
					IsError = true;
					msg = $"二维码:{cage.Id}已经存在,第{i + 2}行与第{dic[cage.Id].Index}行数据重复";
					break;
				}
				else
				{
					dic.Add(cage.Id, (i + 2, cage));
				}
			}
			if (IsError) return (IsError, msg);

			//首先更新鸽笼
			var cages = db.Set<PigeonCage>().ToList();
			var existIds = new HashSet<string>();
			for (int i = 0; i < cages.Count; i++)
			{
				existIds.Add(cages[i].ID);
				var CageNumber = $"{cages[i].Building}-{cages[i].Arrange}-{cages[i].Group}-{cages[i].Number}";
				if (dic.ContainsKey(cages[i].ID))
				{
					var tt = dic[cages[i].ID].Info;
					if (tt.CageNumber != CageNumber)
					{
						IsError = true;
						msg = $"{tt.Id}对于的鸽笼编号{tt.CageNumber}和数据库[{CageNumber}]存在差异，保存不成功";
						break;
					}
					cages[i].temperature = tt.Temperature;
					cages[i].BreedingPigeonCount = tt.PigeonCount.Value;
					cages[i].BreedingPigeonCreateDate = tt.PigeonDate;
				}

			}
			if (IsError) return (IsError, msg);
			var childs = db.Set<PigeonChild>().ToList();
			var chidIds = new HashSet<string>();
			for (int i = 0; i < childs.Count; i++)
			{
				chidIds.Add(childs[i].PigeonHouseId);
				if (dic.ContainsKey(childs[i].PigeonHouseId))
				{
					childs[i].ChildNumber = dic[childs[i].PigeonHouseId].Info.RuGeCount.Value;
				}
			}
			if (IsError) return (IsError, msg);

			var eggs = db.Set<PigeonEgg>().ToList();
			var eggIds = new HashSet<string>();
			for (int i = 0; i < eggs.Count; i++)
			{
				eggIds.Add(eggs[i].PigeonHouseId);
				if (dic.ContainsKey(eggs[i].PigeonHouseId))
				{
					var tt = dic[eggs[i].PigeonHouseId].Info;
					eggs[i].EggNumber = tt.EggCount.Value;
					eggs[i].IsFertilization = tt.IsFertilization.Value;
				}
			}


			for (int i = 0; i < lst.Count; i++)
			{
				var item = lst[i];
				if (!existIds.Contains(item.Id))
				{
					var tt = new PigeonCage
					{
						ID = item.Id,
						Building = item.Building,
						Arrange = item.Arrange,
						Group = item.Group,
						Number = item.Number,
						BreedingPigeonCount = item.PigeonCount.Value,
						NeedMatter = "5,",
						ModifyDate = DateTime.Now,
						ModifyUser = "admin",
						LastChadanDate = DateTime.Now,
						BreedingPigeonCreateDate = DateTime.Now,
						DailyGrams = 0,
						temperature = ""
					};
					db.Set<PigeonCage>().Add(tt);
				}
				if (!chidIds.Contains(item.Id))
				{
					var child = new PigeonChild
					{
						ID = Guid.NewGuid().ToString(),
						IsGrown = false,
						PigeonHouseId = item.Id,
						ChildNumber = item.RuGeCount.Value,
						CreateDate = DateTime.Now,
						DailyGram = 0
					};

					db.Set<PigeonChild>().Add(child);

				}
				if (!eggIds.Contains(item.Id))
				{
					var egg = new PigeonEgg
					{
						ID = Guid.NewGuid().ToString(),
						CreateDate = DateTime.Now,
						EggNumber = item.EggCount.Value,
						IsFertilization = item.IsFertilization.Value,
						IsGrown = false,
						PigeonHouseId = item.Id,
					};

					db.Set<PigeonEgg>().Add(egg);
				}


			}
			if (!IsError) db.SaveChanges();

			return (IsError, msg);
		}

		public Dictionary<string, FeedErrorModel> GetTodayAgvErrorData()
		{
			var today = DateTime.Now.ToString("yyyy-MM-dd");
			using var db = CreateDbContext();
			var lst = db.Set<AGVCarStatusModel>().ToList().Where(x => !string.IsNullOrWhiteSpace(x.CreateTime)
			&& x.CreateTime.Contains(today)
			&& !string.IsNullOrWhiteSpace(x.BarCode)).ToList();

			var res_dic = new Dictionary<string, FeedErrorModel>();

			var dic_1 = new Dictionary<string, AGVCarStatusModel>();
			var dic_2 = new Dictionary<string, AGVCarStatusModel>();
			var dic_3 = new Dictionary<string, AGVCarStatusModel>();
			for (int i = 0; i < lst.Count; i++)
			{
				if (lst[i].FeedNumber == 1)
				{
					if (dic_1.ContainsKey(lst[i].BarCode))
					{
						if (string.Compare(dic_1[lst[i].BarCode].CreateTime, lst[i].CreateTime) < 0)
						{
							dic_1[lst[i].BarCode] = lst[i];
						}
					}
					else
					{

						dic_1.Add(lst[i].BarCode, lst[i]);
					}
				}
				else if (lst[i].FeedNumber == 2)
				{
					if (dic_2.ContainsKey(lst[i].BarCode))
					{
						if (string.Compare(dic_2[lst[i].BarCode].CreateTime, lst[i].CreateTime) < 0)
						{
							dic_2[lst[i].BarCode] = lst[i];
						}
					}
					else
					{

						dic_2.Add(lst[i].BarCode, lst[i]);
					}
				}
				else if (lst[i].FeedNumber == 3)
				{

					if (dic_3.ContainsKey(lst[i].BarCode))
					{
						if (string.Compare(dic_3[lst[i].BarCode].CreateTime, lst[i].CreateTime) < 0)
						{
							dic_3[lst[i].BarCode] = lst[i];
						}
					}
					else
					{

						dic_3.Add(lst[i].BarCode, lst[i]);
					}

				}

			}


			for (int i = 0; i < dic_1.Values.Count; i++)
			{
				var item = dic_1.Values.ElementAt(i);
				var barcode = item.BarCode;
				var barcodes = AppRuntime.GetBarCodeFromCurrentbarCode(barcode);

				//40,40,40,40,0,40,0,40
				var feeds = item.FeedTotal.Replace("[","").Replace("]","").Split(",");
				if (feeds.Length != barcodes.Length) continue;
				var status_0 = item.ServoUseStatus;
				var sifus = new bool[8];
				for (int m = 0; m < 8; m++)
				{
					sifus[m] = (status_0 & 1) == 1; status_0 = status_0 >> 1;
				}
				for (int j = 0; j < barcodes.Length; j++)
				{
					if (res_dic.ContainsKey(barcodes[j])) break;
					var tempVal = int.Parse(feeds[j] ?? "0");
					var model = new FeedErrorModel
					{
						F1 = tempVal,
						FT1 = sifus[j] ? tempVal : 0
					};
					res_dic.Add(barcodes[j], model);
				}

			}
			for (int i = 0; i < dic_2.Values.Count; i++)
			{

				var item = dic_1.Values.ElementAt(i);
				var barcode = item.BarCode;
				var barcodes = AppRuntime.GetBarCodeFromCurrentbarCode(barcode);

				//40,40,40,40,0,40,0,40
				var feeds = item.FeedTotal.Replace("[", "").Replace("]", "").Split(",");
				if (feeds.Length != barcodes.Length) continue;
				var status_0 = item.ServoUseStatus;
				var sifus = new bool[8];
				for (int m = 0; m < 8; m++)
				{
					sifus[m] = (status_0 & 1) == 1; status_0 = status_0 >> 1;
				}
				for (int j = 0; j < barcodes.Length; j++)
				{

					var tempVal = int.Parse(feeds[j] ?? "0");
					if (res_dic.ContainsKey(barcodes[j]))
					{
						res_dic[barcodes[j]].F2 = tempVal;
						res_dic[barcodes[j]].FT2 = sifus[j] ? tempVal : 0;
					}
					else
					{
						var model = new FeedErrorModel
						{
							F2 = tempVal,
							FT2 = sifus[j] ? tempVal : 0
						};
						res_dic.Add(barcodes[j], model);
					}

				}


			}
			for (int i = 0; i < dic_3.Values.Count; i++)
			{
				var item = dic_1.Values.ElementAt(i);
				var barcode = item.BarCode;
				var barcodes = AppRuntime.GetBarCodeFromCurrentbarCode(barcode);

				//40,40,40,40,0,40,0,40
				var feeds = item.FeedTotal.Replace("[", "").Replace("]", "").Split(",");
				if (feeds.Length != barcodes.Length) continue;
				var status_0 = item.ServoUseStatus;
				var sifus = new bool[8];
				for (int m = 0; m < 8; m++)
				{
					sifus[m] = (status_0 & 1) == 1; status_0 = status_0 >> 1;
				}
				for (int j = 0; j < barcodes.Length; j++)
				{

					var tempVal = int.Parse(feeds[j] ?? "0");
					if (res_dic.ContainsKey(barcodes[j]))
					{
						res_dic[barcodes[j]].F3 = tempVal;
						res_dic[barcodes[j]].FT3 = sifus[j] ? tempVal : 0;
					}
					else
					{
						var model = new FeedErrorModel
						{
							F3 = tempVal,
							FT3 = sifus[j] ? tempVal : 0
						};
						res_dic.Add(barcodes[j], model);
					}

				}
			}

			return res_dic;

		}



	}
	public class FeedErrorModel
	{

		public string? barcode { get; set; }
		public int F1 { get; set; }
		public int F2 { get; set; }
		public int F3 { get; set; }
		public int FT1 { get; set; }
		public int FT2 { get; set; }
		public int FT3 { get; set; }

	}
}
